package com.tianlan.blog.dao;

import java.util.List;

import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import com.tianlan.blog.entity.SysResource;

public interface SysResourceDao extends JpaRepository<SysResource, Long>{
	
	@Transactional
	@Modifying
	@Query(value = "UPDATE sys_resource SET del_flag = 1 WHERE id = ?1 OR parent_id = ?1"
	,nativeQuery = true)
	int remove(Integer id);
	
	@Query(value = "SELECT DISTINCT D.id,D.resource_name,D.parent_id,D.resource_key,D.resource_type,D.resource_icon,D.resource_path,D.resource_url,D.resource_cache,D.resource_show,D.resource_level,D.resource_page_name,D.description,D.create_time,D.creator,D.update_time,D.operator,D.del_flag\n" +
		"FROM sys_user A\n" +
		"INNER JOIN sys_user_role B ON A.id = B.user_id AND B.del_flag = '0'\n" +
		"INNER JOIN sys_role_resource C ON B.role_id = C.role_id AND C.del_flag = 0\n" +
		"INNER JOIN sys_resource D ON C.resource_id = D.id AND D.resource_type = 2 AND D.del_flag = '0'\n" +
		"WHERE A.id = :userId AND A.del_flag = 0 ORDER BY D.resource_level"
	,nativeQuery = true)
	List<SysResource> queryResourceByUserId(@Param("userId") Integer userId);
	
	@Query(value = "SELECT s.* FROM sys_resource s WHERE s.id in (:resourceIds) AND s.del_flag = '0'"
	,nativeQuery = true)
	List<SysResource> getSysResource(@Param("resourceIds") List<Integer> resourceIdS);
	
    /**
     * queryResourceTreeProc
     * @Title: queryResourceTreeProc
     * @Description: 查询登陆用户的许可权限(使用存储过程递归查询所有权限树信息)
     * @param parentId
     * @return List<SysResource>
     */
	@Query(value = "CALL queryResourceList(:parentId)"
	,nativeQuery = true)
	List<SysResource> queryResourceTreeProc(@Param("parentId") Integer parentId);
	
	long countByResourceKeyAndDelFlag(String resourceKey,String delFlag);
	long countByIdAndDelFlag(Integer id,String delFlag);
	long countByIdOrParentIdAndDelFlag(Integer Id,Integer parentId,String delFlag);
	long count(Specification<SysResource> specification);
}
